package com.xkdx.guangguang.fragment.brand.photo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentManager;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.xkdx.caipiao.R;
import com.xkdx.guangguang.BrandUpLoadPhotoChoiceActivity;
import com.xkdx.guangguang.ManagerActivity;
import com.xkdx.guangguang.fragment.BaseFragment;
import com.xkdx.guangguang.fragment.shop.photo.PhotoViewFlipperFragment;
import com.xkdx.guangguang.fragment.shop.uploadphoto.BrandUploadPhotoFragment;
import com.xkdx.guangguang.module.network.AbsModule;
import com.xkdx.guangguang.module.statics.IConstants;
import com.xkdx.guangguang.shareclass.Photo;
import com.xkdx.guangguang.shareclass.PhotoAlbum;
import com.xkdx.guangguang.util.SharePrefenceUtil;

public class BrandPhotoAlbumFragment extends BaseFragment implements
		OnClickListener {

	private Button back, photo_upLoad;
	private TextView brand_photo_all, brand_photo_dianmian,
			brand_photo_product, brand_photo_huodong, brand_photo_others,
			loading_more;
	private int PageIndex = 1;
	private int PageSize = 6;
	private Bundle b;
	private String brandID;
	private PhotoAlbum photoAlbum;
	private ImageView brand_no_photo_im;

	private View view;

	private ImageLoader imageLoader = ImageLoader.getInstance();
	private DisplayImageOptions options;

	private BrandPhotosAction brandPhotosAction;
	private BrandPhotosModule brandPhotosModule;
	private BrandPhotosPresistence brandPhotosPresistence;

	/**
	 * 自定义控件相关变量
	 */
	private ScrollView sv;
	private LinearLayout ll, llfooter;
	private MyGridView myGridView;
	private GridItemAdapter adapter;

	private List<Photo> list_temp;// 存放全部图片信息
	private List<Photo> list_group; // 6组请求一次
	private int count = 0;

	private List<Photo> list_dianmian; // 存放店面信息
	private List<Photo> list_product; // 存放产品信息
	private List<Photo> list_huodong; // 存放活动信息
	private List<Photo> list_others; // 存放其他信息
	private int index = 0;
	private int scrollY = 0;
	private int scrollX = 0;
	boolean isScoll = false;
	//LinearLayout refresh_ll;
	private HashMap<Integer, List<Photo>> list_map = new HashMap<Integer, List<Photo>>();

	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		options = new DisplayImageOptions.Builder()
				.showStubImage(R.drawable.empty_photo)
				.showImageForEmptyUri(R.drawable.empty_photo)
				.showImageOnFail(R.drawable.empty_photo).cacheInMemory()
				.cacheOnDisc().build();
		b = getArguments();
		brandID = b.getString("brandID");
		IConstants.isBrandPhotoComment = false;
		IConstants.isUpLoadBrandPhoto = false;
		list_temp = new ArrayList<Photo>(); // 存放全部数据

		// 存放店面信息
		list_dianmian = new ArrayList<Photo>();

		// 存放产品信息
		list_product = new ArrayList<Photo>();

		// 存放活动信息
		list_huodong = new ArrayList<Photo>();
		// 存放其他信息
		list_others = new ArrayList<Photo>();

		list_group = new ArrayList<Photo>();

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		view = inflater.inflate(R.layout.brand_photo_album, container, false);

		findView();
		setOnClick();

		// 如果从品牌焦点图跳转或上传成功页面跳转，则重新加载全部页面
		if (IConstants.isFromInfo || IConstants.isUpLoadBrandPhoto) {
			IConstants.isFromInfo = false;
			IConstants.isUpLoadBrandPhoto = false;
			showLoading();
		} else { // 如果从相册详情页面返回或没有成功上传图片，则重新返回该页面
			setImageResouce(index);
			setGridValueState(list_map.get(index));
		}

		return view;
	}

	@Override
	public void findView() {

		IConstants.hideInputMethodAways(getActivity(), view);
		loading_more = (TextView) view.findViewById(R.id.loading_more);
		back = (Button) view.findViewById(R.id.back_focuse_ims);
		photo_upLoad = (Button) view.findViewById(R.id.photo_update);
		brand_photo_all = (TextView) view.findViewById(R.id.brand_photo_all);
		brand_photo_dianmian = (TextView) view
				.findViewById(R.id.brand_photo_dianmian);
		brand_photo_product = (TextView) view
				.findViewById(R.id.brand_photo_product);
		brand_photo_huodong = (TextView) view
				.findViewById(R.id.brand_photo_huodong);
		brand_photo_others = (TextView) view
				.findViewById(R.id.brand_photo_others);
		brand_no_photo_im = (ImageView) view
				.findViewById(R.id.brand_no_photo_im);

		sv = (ScrollView) view.findViewById(R.id.MainGridViewScroll);
		ll = (LinearLayout) view.findViewById(R.id.MainGridViewScrollLinear);
		myGridView = (MyGridView) view.findViewById(R.id.MainGridViewGrid);
		llfooter = (LinearLayout) view
				.findViewById(R.id.MainGridViewFooterLinear);

		//refresh_ll = (LinearLayout) view.findViewById(R.id.refresh_ll);

		llfooter.setVisibility(View.GONE);
		sv.setOnTouchListener(new OnTouchListener() {
			private int lastY = 0;
			private int touchEventId = -9983761;
			Handler handler = new Handler() {
				@Override
				public void handleMessage(Message msg) {
					super.handleMessage(msg);
					View scroller = (View) msg.obj;
					if (msg.what == touchEventId) {
						if (lastY == scroller.getScrollY()) {
							handleStop(scroller);
						} else {
							handler.sendMessageDelayed(handler.obtainMessage(
									touchEventId, scroller), 1);
							lastY = scroller.getScrollY();
						}
					}
				}
			};

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				isScoll = false;
				int eventAction = event.getAction();
				int y = (int) event.getRawY();
				switch (eventAction) {
				case MotionEvent.ACTION_UP:
					if (Math.abs(lastY - y) < 20) {
					} else {
						handler.sendMessageDelayed(
								handler.obtainMessage(touchEventId, v), 5);
					}
					break;
				default:
					break;
				}
				return false;
			}

			// 这里写真正的事件
			private void handleStop(Object view) {
				lastY = sv.getScrollY();
				scrollY = sv.getScrollY();
				if (lastY == (ll.getHeight() - sv.getHeight())) {

					if (llfooter.isEnabled()) {
						addMoreData(index, list_map.get(index));
					}
				}
			}
		});

		adapter = new GridItemAdapter(getActivity(), list_group, imageLoader);
		myGridView.setAdapter(adapter);
		myGridView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					final int position, long id) {
				photoAlbum.setList(list_group);
				intentToViewFlipper(position);
			}
		});

		brandPhotosModule = new BrandPhotosModule();

	}

	/**
	 * 加载更多
	 */

	protected void addMoreData(int index, List<Photo> list) {
		int num = 0;
		PageIndex++;

		if (list != null) {
			count = list.size();
			for (int i = (PageIndex - 1) * PageSize; i < count
					&& i < (PageIndex * PageSize); i++) {
				list_group.add(list.get(i));
				num++;
			}
		}

		if (num < PageSize) {

			setLoadingMoreState();
		} else {
			setLoadingStateEnable();
		}
		// adapter = new GridItemAdapter(getActivity(), list_group,
		// imageLoader);
		// myGridView.setAdapter(adapter);
		adapter.notifyDataSetChanged();

	}

	/**
	 * 根据加载的图片数目设置加载更多状态
	 */
	public void setLoadingMoreState() {
		loading_more.setText(getResources().getString(
				R.string.brand_photo_noloading));
		llfooter.setEnabled(false);

	}

	/**
	 * 根据加载的图片数目设置加载更多状态
	 */
	public void setLoadingStateEnable() {
		loading_more.setText(getResources().getString(
				R.string.brand_photo_loading));
		llfooter.setEnabled(true);

	}

	@Override
	public void setOnClick() {

		back.setOnClickListener(this);
		photo_upLoad.setOnClickListener(this);
		brand_photo_all.setOnClickListener(this);
		brand_photo_dianmian.setOnClickListener(this);
		brand_photo_product.setOnClickListener(this);
		brand_photo_huodong.setOnClickListener(this);
		brand_photo_others.setOnClickListener(this);
		brand_no_photo_im.setOnClickListener(this);
		llfooter.setOnClickListener(this);
		//refresh_ll.setOnClickListener(this);

	}

	@Override
	public void onResume() {
		super.onResume();
		if (BrandUpLoadPhotoChoiceActivity.brandUpLoadPicture != null) {
			BrandUploadPhotoFragment uploadPhotoFragment = new BrandUploadPhotoFragment();
			Bundle b = new Bundle();
			b.putString("brandID", brandID);
			uploadPhotoFragment.setArguments(b);
			getFragmentManager().beginTransaction()
					.replace(R.id.fragment, uploadPhotoFragment)
					.addToBackStack(null).commit();
		}

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.brand_photo_all: // 全部
			index = 0;
			setImageResouce(index);
			PageIndex = 1;

			setGridValue(list_temp);
			break;
		case R.id.brand_photo_dianmian: // 店面
			index = 1;
			setImageResouce(index);
			PageIndex = 1;
			setGridValue(list_dianmian);
			break;
		case R.id.brand_photo_product: // 产品
			PageIndex = 1;
			index = 2;

			setImageResouce(index);

			setGridValue(list_product);
			break;
		case R.id.brand_photo_huodong: // 活动
			PageIndex = 1;
			index = 3;

			setImageResouce(index);

			setGridValue(list_huodong);
			break;
		case R.id.brand_photo_others: // 其他

			index = 4;
			setImageResouce(index);
			PageIndex = 1;
			setGridValue(list_others);
			break;

		case R.id.back_focuse_ims:
			FragmentManager fm = getFragmentManager();
			fm.popBackStack();
			break;

		case R.id.photo_update: // 图片上传
			SharePrefenceUtil su = new SharePrefenceUtil(getActivity(),
					IConstants.SP_USER);
			String loginToken = su.getUserLoginToken();
			if (!loginToken.equals("")) {
				Intent intent = new Intent(getActivity(),
						BrandUpLoadPhotoChoiceActivity.class);
				startActivity(intent);

			} else {
				UserLogin();
			}
			break;

		case R.id.brand_no_photo_im:
			SharePrefenceUtil su1 = new SharePrefenceUtil(getActivity(),
					IConstants.SP_USER);
			String loginToken1 = su1.getUserLoginToken();
			if (!loginToken1.equals("")) {
				Intent intent = new Intent(getActivity(),
						BrandUpLoadPhotoChoiceActivity.class);
				startActivity(intent);

			} else {
				UserLogin();
			}
			break;

		case R.id.MainGridViewFooterLinear:
			if (llfooter.VISIBLE == view.VISIBLE) {
				if (llfooter.isEnabled()) {
					addMoreData(index, list_map.get(index));
				}
				break;
			}

//		case R.id.refresh_ll:
//			refresh_ll.setVisibility(View.GONE);
//			showLoading();
//			break;
		default:
			break;
		}

	}

	/**
	 * 在不刷新本页面的基础上，重新定位gridview,保存状态
	 * 
	 * @param list
	 *            <Photo>
	 */
	private void setGridValueState(final List<Photo> list) {

		int num = 0;
		if (list != null) {
			for (int i = (PageIndex - 1) * PageSize; i < list.size()
					&& i < PageIndex * PageSize; i++) {
				num++;
			}
		}

		if (num == 0) {
			brand_no_photo_im.setVisibility(View.VISIBLE);
			sv.setVisibility(View.GONE);
		} else if (num < PageSize) {
			llfooter.setVisibility(View.VISIBLE);
			sv.setVisibility(View.VISIBLE);
			brand_no_photo_im.setVisibility(View.GONE);
			setLoadingMoreState();
		} else {
			sv.setVisibility(View.VISIBLE);
			llfooter.setVisibility(View.VISIBLE);
			brand_no_photo_im.setVisibility(View.GONE);
			setLoadingStateEnable();
		}
		if (IConstants.isBrandPhotoComment) {
			for (int i = 0; i < list.size(); i++) {

				if (IConstants.singlePhotoComment.containsKey(list_group.get(i)
						.getPhotoID())) {
					list.get(i).setCommentCount(
							IConstants.singlePhotoComment.get(list_group.get(i)
									.getPhotoID()));
					list_group.get(i).setCommentCount(
							IConstants.singlePhotoComment.get(list_group.get(i)
									.getPhotoID()));
					IConstants.isBrandPhotoComment = false;
				}
			}
		}

		adapter.notifyDataSetChanged();

		sv.post(new Runnable() {
			public void run() {
				sv.scrollTo(0, scrollY);
			}
		});

		myGridView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					final int position, long id) {
				photoAlbum.setList(list);
				intentToViewFlipper(position);
			}
		});
	}

	/**
	 * 填充gridview，切换按钮重新填充gridview
	 * 
	 * @param list
	 *            <Photo>
	 */
	private void setGridValue(final List<Photo> list) {
		list_group.clear();
		int num = 0;
		for (int i = (PageIndex - 1) * PageSize; i < list.size()
				&& i < PageSize; i++) {
			list_group.add(list.get(i));
			num++;
		}

		if (num == 0) {
			brand_no_photo_im.setVisibility(View.VISIBLE);
			sv.setVisibility(View.GONE);
		} else if (num < PageSize) {
			llfooter.setVisibility(View.VISIBLE);
			brand_no_photo_im.setVisibility(View.GONE);
			sv.setVisibility(View.VISIBLE);
			setLoadingMoreState();
		} else {
			sv.setVisibility(View.VISIBLE);
			llfooter.setVisibility(View.VISIBLE);
			brand_no_photo_im.setVisibility(View.GONE);
			setLoadingStateEnable();
		}
		// adapter = new GridItemAdapter(getActivity(), list_group,
		// imageLoader);
		//
		// myGridView.setAdapter(adapter);
		adapter.notifyDataSetChanged();

		myGridView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					final int position, long id) {
				photoAlbum.setList(list);
				intentToViewFlipper(position);
			}
		});
	}

	/**
	 * 切换按钮，改变按钮背景
	 * 
	 * @param i
	 */
	private void setImageResouce(int i) {
		if (i == 0) {
			brand_photo_all.setBackgroundResource(R.drawable.brand_photo_bj);
			brand_photo_dianmian.setBackgroundResource(0);
			brand_photo_product.setBackgroundResource(0);
			brand_photo_huodong.setBackgroundResource(0);
			brand_photo_others.setBackgroundResource(0);
		} else if (i == 1) {
			brand_photo_dianmian
					.setBackgroundResource(R.drawable.brand_photo_bj);
			brand_photo_all.setBackgroundResource(0);
			brand_photo_product.setBackgroundResource(0);
			brand_photo_huodong.setBackgroundResource(0);
			brand_photo_others.setBackgroundResource(0);
		} else if (i == 2) {
			brand_photo_product
					.setBackgroundResource(R.drawable.brand_photo_bj);
			brand_photo_dianmian.setBackgroundResource(0);
			brand_photo_all.setBackgroundResource(0);
			brand_photo_huodong.setBackgroundResource(0);
			brand_photo_others.setBackgroundResource(0);
		} else if (i == 3) {
			brand_photo_huodong
					.setBackgroundResource(R.drawable.brand_photo_bj);
			brand_photo_dianmian.setBackgroundResource(0);
			brand_photo_product.setBackgroundResource(0);
			brand_photo_all.setBackgroundResource(0);
			brand_photo_others.setBackgroundResource(0);
		} else if (i == 4) {
			brand_photo_others.setBackgroundResource(R.drawable.brand_photo_bj);
			brand_photo_dianmian.setBackgroundResource(0);
			brand_photo_product.setBackgroundResource(0);
			brand_photo_huodong.setBackgroundResource(0);
			brand_photo_all.setBackgroundResource(0);
		}

	}

	@Override
	public void showLoading() {
		list_temp.clear();
		list_group.clear();
		setLoadingStateEnable();
		PageIndex = 1;
		brandPhotosAction = new BrandPhotosAction(brandID);
		brandPhotosPresistence = new BrandPhotosPresistence(this);

		((ManagerActivity) getActivity())
				.addCurrentTask(brandPhotosPresistence);
		brandPhotosPresistence.setActitons(brandPhotosAction);
		brandPhotosPresistence.setModule(brandPhotosModule);
		brandPhotosPresistence.execute();
		dataLoadDialog.setOnCancelListener(new OnCancelListener() {

			@Override
			public void onCancel(DialogInterface dialog) {
				if (brandPhotosPresistence != null) {
					brandPhotosPresistence.cancel(true);
				}
				getFragmentManager().popBackStack();

			}
		});
		dataLoadDialog.show();
	}

	/**
	 * 请求结束
	 */
	@Override
	public void showLoaded(HashMap<String, AbsModule> map) {
		dataLoadDialog.dismiss();

		if (map.containsKey("0")) {
			photoAlbum = brandPhotosModule.photoAlbum;
			count = photoAlbum.getList().size();
			if (count != 0) {

				list_temp = photoAlbum.getList(); // 全部信息
				list_dianmian.clear();
				list_product.clear();
				list_huodong.clear();
				list_others.clear();
				list_map.clear();

				list_map.put(0, list_temp);

				for (int i = 0; i < count; i++) {

					// 店面集合
					if (list_temp.get(i).getGalleryName().equals("1")) {
						list_dianmian.add(list_temp.get(i));

					}
					// 产品集合
					if (list_temp.get(i).getGalleryName().equals("2")) {
						list_product.add(list_temp.get(i));
					}
					// 活动集合
					if (list_temp.get(i).getGalleryName().equals("3")) {
						list_huodong.add(list_temp.get(i));
					}
					// 其他集合
					if (list_temp.get(i).getGalleryName().equals("4")) {
						list_others.add(list_temp.get(i));
					}

					list_map.put(1, list_dianmian);
					list_map.put(2, list_product);
					list_map.put(3, list_huodong);
					list_map.put(4, list_others);

				}

				int num = 0;
				for (int i = (PageIndex - 1) * PageSize; i < count
						&& i < PageSize; i++) {
					list_group.add(list_temp.get(i));
					num++;
				}

				llfooter.setVisibility(View.VISIBLE);
				if (num < PageSize) {
					sv.setVisibility(View.VISIBLE);
					llfooter.setVisibility(View.VISIBLE);
					brand_no_photo_im.setVisibility(View.GONE);
					setLoadingMoreState();
				} else {
					brand_no_photo_im.setVisibility(View.GONE);
					sv.setVisibility(View.VISIBLE);
					llfooter.setVisibility(View.VISIBLE);
					setLoadingStateEnable();
				}
				// adapter = new GridItemAdapter(getActivity(), list_group,
				// imageLoader);
				//
				// myGridView.setAdapter(adapter);
				adapter.notifyDataSetChanged();
				myGridView.setOnItemClickListener(new OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> parent, View view,
							final int position, long id) {
						intentToViewFlipper(position);
					}
				});
			} else {
				brand_no_photo_im.setVisibility(View.VISIBLE);
				sv.setVisibility(View.GONE);
				Toast.makeText(getActivity(), "没有图片", Toast.LENGTH_SHORT)
						.show();

			}

		} else {
			 IConstants.isFromInfo = true;
			  showErrorTip(map);
			 refresh(map);
			//refresh_ll.setVisibility(View.VISIBLE);

		}

	}

	/**
	 * 跳转到图片详情页面
	 * 
	 * @param position
	 */
	private void intentToViewFlipper(int position) {
		PhotoViewFlipperFragment photoViewFlipperFragment = new PhotoViewFlipperFragment();
		Bundle b = new Bundle();
		b.putSerializable("photoAlbum", photoAlbum);
		b.putInt("position", position);
		photoViewFlipperFragment.setArguments(b);
		getFragmentManager().beginTransaction()
				.replace(R.id.fragment, photoViewFlipperFragment)
				.addToBackStack(null).commit();
	}

	@Override
	public void onPause() {
		imageLoader.stop();
		// if (adapter != null) {
		// adapter = null;
		// }
		// myGridView.removeAllViews();
		super.onPause();
	}

	@Override
	public void showClick(HashMap<String, AbsModule> map) {

	}

	@Override
	public void showLoadMore(HashMap<String, AbsModule> map) {

	}

}
